<?php

namespace app\admin\controller\commodity;
use app\admin\model\Commodity as CommodityModel;
use app\common\controller\Backend;
use jueqi\Tree;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class Index extends Backend
{
    /**
     * @var CommodityModel
     */
    protected $model = null;
    /**
     * 新增/编辑时，对前端发送的字段进行排除（忽略不入库）
     * @var string[]
     */
    protected $preExcludeFields = ['id', 'create_time', 'update_time'];
    /**
     * 快速搜索字段
     * @var string[]
     */
    protected $quickSearchField = ['name'];

    /**
     * 开启数据限制
     */
    protected $dataLimit = 'allAuthAndOthers';

    protected $dataLimitField = 'admin_id';

    /**
     * 查看请求返回的主表字段控制
     */
    protected $indexField = ['id', 'name', 'img', 'weight', 'category', 'create_time'];
    /**
     * 是否组装Tree
     * @var bool
     */
    protected $assembleTree;
    /**
     * @var Tree
     */
    protected $tree = null;
    public function initialize()
    {
        parent::initialize();
        $this->model = new CommodityModel();
    }

    public function select()
    {
        $data = $this->getSelectData([], 'id,name');
        if ($this->assembleTree) {
            $data = $this->tree->assembleTree($this->tree->getTreeArray($data));
        }
        $this->success('', [
            'options' => $data
        ]);
    }

    public function getSelectData($where = [], $field = '*'): array
    {
        try {
            try {
                $data = $this->model->field($field)->where($where)->select()->toArray();
            } catch (DataNotFoundException|ModelNotFoundException|DbException $ex) {
                $data = array();
            }
            // 如果要求树状，此处先组装好 children
            return $this->assembleTree ? $this->tree->assembleChild($data) : $data;
        } catch (DbException $ex) {
            // 如果要求树状，此处先组装好 children
            return [];
        }
    }
}